package com.hfxt.controller;

import com.hfxt.constants.Constants;
import com.hfxt.constants.ResultEnum;
import com.hfxt.dto.BaseException;
import com.hfxt.dto.Result;
import com.hfxt.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/api/sms")
@RestController
public class SmsController {

    @Autowired
    private SmsUtils smsUtils;
    @Autowired
    private RedisUtils redisUtils;

    @RequestMapping("/verifyCode")
    public Result verifyCode(String phone, Integer codeType) throws Exception {
        //判断手机号和验证码类型是否为空
        // 放在拦截器里ValidateParamInterceptor

        //判断手机号是否符合格式  Constants
        if (!phone.matches(Constants.RegConstant.PHONE_REGSTR)) {
            throw new BaseException(ResultEnum.PHONE_ERROR);
        }
        //判断验证码类型是否符合固定取值( Constants里Sms约束 0.1.2)
        if (codeType != Constants.Sms.CodeType.LOGIN_OR_REGISTER && codeType != Constants.Sms.CodeType.PASS_UPDATE && codeType != Constants.Sms.CodeType.ORDER_NOTICE) {
            throw new BaseException(ResultEnum.CODE_TYPE_ERROR);
        }
        //构造存储在redis中的key  (redis按照键值对存储，key不能重复  添加前缀项目名-功能名-唯一值（手机号）-短信类型codetype转成字符串)
        String key = StringUtil.formatKeyWithPrefix(Constants.RedisKey.PROJECT_PRIFIX, Constants.RedisKey.SMS_PRIFIX, phone, codeType + "");
        //判断距离上次发送该类型验证码是否超过60s
        String value = redisUtils.getValue(key);
        if (!StringUtil.isBlank(value)) {
            throw new BaseException(ResultEnum.CODE_SEND_ERROR);
        }
        //将验证码保存至服务器redis
        String code = MathUtils.random();
        redisUtils.set(key, code, Constants.Duration.MINUTE_INT);
        //发送短信验证码
        boolean flag = smsUtils.sendMessage(phone, Constants.Sms.TemplateCode.LOGIN_OR_REGISTER, code);  //电话号码，模板，文字
        return flag ? ResultUtils.returnSuccess() : ResultUtils.returnFail();
    }
}
